from django.shortcuts import render
from django.http import HttpResponse,JsonResponse

from .. models import Goods,Types
import os
from web.settings import BASE_DIR
from . TypesViews import GetTypesAll
from . UserViews import uploads
from django.contrib.auth.decorators import permission_required


# 商品列表
@permission_required('myadmin.show_goods',raise_exception=True)
def list(request):
    # 获取所有的会员数据
    obj = Goods.objects.filter()
    # 获取搜索的类型
    types = request.GET.get('type',None)
    # print(types)
    # 判断是否有搜索条件
    if types:
        # 获取搜索的关键字
        keywords = request.GET.get('keywords')
        if types == 'tid':
            # 获取分类中名字包含 关键字的 对象
            obj = obj.filter(tid__name__contains=keywords)
        else:  
            # 拼接条件参数
            data = {types +'__contains':keywords}
            # 执行条件搜索
            # print(data) {'tid__contains': '魅蓝'}
            obj = obj.filter(**data)

    # 数据分页
    # 获取当前页的页数
    pageindex = request.GET.get('p',1)
    # 导入分页类
    from django.core.paginator import Paginator
    # 实例化分页对象
    p = Paginator(obj, 2)
    # 获取当前页的 数据
    goodslist = p.page(pageindex)
    # 分配数据
    context = {'goodslist':goodslist}
    # 加载模板
    return render(request,'admin/goods/list.html',context)

# 商品添加页面
@permission_required('myadmin.insert_goods',raise_exception=True)
def add(request):

    context = {'typelist':GetTypesAll(request)}
    
    return render(request,'admin/goods/add.html',context)

# 执行商品添加
@permission_required('myadmin.insert_goods',raise_exception=True)
def insert(request):

    # 获取数据
    # 获取数据
    data = request.POST.dict()
    del data['csrfmiddlewaretoken']

    # 判断是否有文件上传
    myfile = request.FILES.get('pic',None)
    if myfile:
        # 上传图片　ｕｐｌｏａｄｓ
        data['pic'] = uploads(myfile)
    else:
        return HttpResponse('<script>alert("必须上传图片");history.back(-1)</script>')

    # 商品分类为一对多，需要使用外键，所以创建时外键的值要求是个对象
    data['tid'] = Types.objects.get(id=data['tid'])

    # 执行添加
    res = Goods.objects.create(**data)
    if res:
        return HttpResponse('<script>alert("商品添加成功");location.href="/myadmin/goods/list"</script>')
    else:
        return HttpResponse('<script>alert("商品添加失败");history.back(-1)</script>')


# 执行商品删除
@permission_required('myadmin.del_goods',raise_exception=True)
def delete(request):
    if request.is_ajax():
        try:
            # 获取id，执行逻辑删除
            obj = Goods.objects.get(id = request.GET['id'])
            obj.isDelete = True
            obj.save()
            return JsonResponse({'code':1,'msg':'下架成功'})
        except:
            return JsonResponse({'code':0,'msg':'下架失败'})
    else:
        # 返回一个404的错误页面
        raise Http404('没有找到～')


# 商品编辑
@permission_required('myadmin.edit_goods',raise_exception=True)
def edit(request,gid):
    # 获取会员对象
    ob = Goods.objects.get(id=gid)
    # 分配数据
    context = {'ginfo':ob,'editlist':GetTypesAll(request)}
    # 加载模板
    return render(request,'admin/goods/edit.html',context)


# 执行商品的更新
# 执行商品修改
@permission_required('myadmin.update_goods',raise_exception=True)
def update(request):
   # 获取数据
    data = request.POST.dict()
    del data['csrfmiddlewaretoken']
    # 获取会员对象
    ob = Goods.objects.get(id=data['id'])
    ob.title = data['title']
    ob.price = data['price']
    ob.store = data['store']
    ob.info = data['info']
    # 判断是否更新了头像
    myfile = request.FILES.get('pic',None)
    if myfile:
        # 删除原来的头像
        os.remove(BASE_DIR+ob.pic)
        # 上传新的头像
        ob.pic = uploads(myfile)

    # 执行更新
    ob.save()
    return HttpResponse('<script>alert("更新成功");location.href="/myadmin/goods/list/"</script>')







